package com.example.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.unit.DataUnit;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.entity.Student;
import com.example.mapper.AdminMapper;
import com.example.mapper.StudentMapper;
import org.apache.tomcat.jni.User;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Component
public class TokenUtils {
    private static StudentMapper staticStudentMapper;
    @Resource
    StudentMapper studentMapper;
    @PostConstruct
    public void setUserService(){
        staticStudentMapper = studentMapper;
    }

    public  static  String genToken(String userId,String sign){
        return JWT.create().withAudience(userId)
                .withExpiresAt(DateUtil.offsetHour(new Date(),2))
                .sign(Algorithm.HMAC256(sign)); //以password作为密钥
    }

    public static Student getCurrentUser(){
        try{
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            if (StrUtil.isNotBlank(token)){
                String userId = JWT.decode(token).getAudience().get(0);
                return staticStudentMapper.selectById(Integer.valueOf(userId));
            }
        } catch (Exception e){
            return  null;
        }
        return null;
    }
}
